package com.zxy.hotel.config;

import com.zxy.hotel.util.JwtUtil;
import freemarker.template.utility.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 14995
 * @description
 * @create 2021-12-13 下午 5:56
 */
public class JwtAuthFilter extends OncePerRequestFilter {

    public JwtAuthFilter(@Autowired UserDetailsService userDetailsService){
        this.userDetailsService = userDetailsService;
    }
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (StringUtils.hasText(token) && token.startsWith("Bearer")) {
            token = token.substring("Bearer".length());
            String username = JwtUtil.getUserInfoFromToken(token);
            //如果用户名不为空但是认证对象为空
            if (StringUtils.hasText(username) && null == SecurityContextHolder.getContext().getAuthentication()) {
                //根据用户名获取用户对象
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //给SpringSecurity全局上下文设置当前登录用户对象
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
